package com.example.nfc.activity;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.AlertDialog;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.example.nfc.MyApp;
import com.example.nfc.ProgressDialog;
import com.example.nfc.R;
import com.example.nfc.adapter.GgjsyztAdapter;
import com.example.nfc.base.BaseNfcActivity;
import com.example.nfc.server.network.http.HttpException;
import com.example.nfc.server.request.JeDoUpdateRequest;
import com.example.nfc.server.request.JeLoadRequest;
import com.example.nfc.server.response.JeDoUpdateRespone;
import com.example.nfc.server.response.JeLoadRespone;
import com.example.nfc.server.response.Rows;
import com.example.nfc.widget.refreshLayout.MaterialSmoothRefreshLayout;
import com.example.nfc.widget.refreshLayout.lib.SmoothRefreshLayout;
import com.rscja.deviceapi.RFIDWithUHF;
import com.rscja.deviceapi.entity.SimpleRFIDEntity;
import com.rscja.utility.StringUtility;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 钢构件使用状态
 */
public class GgjsyztActivity extends BaseNfcActivity {

    private GgjsyztAdapter adapter;
    @Bind(R.id.refreshLayout)
    MaterialSmoothRefreshLayout refreshLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ggjsyzt);
        ButterKnife.bind(this);
        refreshLayout.setDisableLoadMore(true);
        refreshLayout.setEnableAutoRefresh(false);
        refreshLayout.setOnRefreshListener(new SmoothRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefreshing() {
                jeLoadRequest = new JeLoadRequest();
                jeLoadRequest.setFuncCode("INFO");
                jeLoadRequest.setFuncId("w7oYHEhqHv2ikgi30f2");
                jeLoadRequest.setColumnLazy("true");
                jeLoadRequest.setMark("false");
                jeLoadRequest.setPostil("");
                jeLoadRequest.setFuncEdit("false");
                jeLoadRequest.setCoverJquery("0");
                jeLoadRequest.setTableCode("INFO");
                jeLoadRequest.set_isFunc_("true");
                jeLoadRequest.setJ_query("%7B%22custom%22%3A%5B%5D%2C%22_custom_types%22%3A%5B%5D%7D");
                jeLoadRequest.setJ_order("%5B%5D");
                jeLoadRequest.setPage("1");
                jeLoadRequest.setStart("0");
                jeLoadRequest.setLimit("3000");
                request(GET_DATA);
            }

            @Override
            public void onLoadingMore() {

            }
        });
        refreshLayout.setDisableLoadMoreWhenContentNotFull(true);
        refreshLayout.setEnableAutoLoadMore(false);
        refreshLayout.autoRefresh(true);
        refreshLayout.autoLoadMore(false);

        adapter = new GgjsyztAdapter(mContext, new GgjsyztAdapter.ClickCallBack() {
            @Override
            public void btn1(int position) {
                Rows rows = adapter.getItem(position);
                update(rows.getINFO_ID(),"xz");
            }

            @Override
            public void btn2(int position) {
                Rows rows = adapter.getItem(position);
                update(rows.getINFO_ID(),"sy");
            }

            @Override
            public void btn3(int position) {
                Rows rows = adapter.getItem(position);
                update(rows.getINFO_ID(),"sh");
            }

            @Override
            public void btn4(int position) {
                Rows rows = adapter.getItem(position);
                update(rows.getINFO_ID(),"djc");
            }

            @Override
            public void btn5(int position) {
                Rows rows = adapter.getItem(position);
                update(rows.getINFO_ID(),"yc");
            }
        });
        lv.setLayoutManager(new LinearLayoutManager(mContext));
        lv.setHasFixedSize(true);
        lv.setAdapter(adapter);


        initSound();
        init();
    }





    public void update(String id,String zt){
        updateRequest = new JeDoUpdateRequest();
        updateRequest.setFuncCode("INFO");
        updateRequest.setFuncEdit("true");
        updateRequest.setJeFileType("PROJECT");
        updateRequest.setCodeGenFieldInfo("%5B%5D");
        updateRequest.setTableCode("INFO");
        updateRequest.setFuncType("func");
        updateRequest.setViewTableCode("");
        updateRequest.setViewConfigInfo("");
        updateRequest.setUploadableFields("");
        updateRequest.setBatchFilesFields("");
        updateRequest.setFilePath("");
        updateRequest.setINFO_ZT(zt);
        updateRequest.setINFO_ID(id);
        ProgressDialog.show(GgjsyztActivity.this,"更新中...");
        request(UPDATE);
    }

    @Bind(R.id.lv)
    RecyclerView lv;

    @Bind(R.id.leftBtn)
    LinearLayout leftBtn;
    @OnClick(R.id.leftBtn)
    public void leftBtnClick(){
        finish();
    }

    private static final int GET_DATA = 1010;
    private static final int UPDATE = 1002;
    private JeLoadRequest jeLoadRequest;
    private JeDoUpdateRequest updateRequest;
    @Override
    public Object doInBackground(int requestCode, String parameter) throws HttpException {
        switch (requestCode){
            case GET_DATA:
                return action.getDataRequest(jeLoadRequest);
            case UPDATE:
                return action.updateDataRequest(updateRequest);
        }
        return super.doInBackground(requestCode, parameter);
    }

    @Override
    public void onSuccess(int requestCode, Object result) {
        super.onSuccess(requestCode, result);
        switch (requestCode){
            case GET_DATA:
                JeLoadRespone respone = (JeLoadRespone)result;
                refreshLayout.refreshComplete(true);
                if("1000".equals(respone.getCode())){
                    adapter.update(respone.getRows());
                }else{
                    shortToast(respone.getMessage());
                }
                break;
            case UPDATE:
                ProgressDialog.disMiss();
                JeDoUpdateRespone updateRespone = (JeDoUpdateRespone)result;
                shortToast(updateRespone.getMessage());
                if("1000".equals(updateRespone.getCode())){
                    adapter.updateById(updateRespone.getObj().getINFO_ID(),updateRespone.getObj().getINFO_ZT());
                }
                break;
        }
    }

    @Override
    public void onFailure(int requestCode, int state, Object result) {
        super.onFailure(requestCode, state, result);
        switch (requestCode){
            case UPDATE:
                ProgressDialog.disMiss();
                break;
        }
    }

    @OnClick(R.id.scan)
    public void shaomiao(){
        read();
        //select("23423234233");
    }

    public void select(String id){
        final int position = adapter.findPositionById(id);
        lv.post(new Runnable() {
            @Override
            public void run() {
                lv.smoothScrollToPosition(position);
                adapter.setSelected(position);
            }
        });
    }







    private AlertDialog dialog;
    private long[] timeArr;
    public RFIDWithUHF mReader;
    private int index = 0;
    private void init(){
        try {
            mReader = RFIDWithUHF.getInstance();
        } catch (Exception ex) {
            shortToast(ex.getMessage());
            return;
        }

        if (mReader != null) {
            new InitTask().execute();
        }
    }

    public class InitTask extends AsyncTask<String, Integer, Boolean> {
        android.app.ProgressDialog mypDialog;

        @Override
        protected Boolean doInBackground(String... params) {
            // TODO Auto-generated method stub
            return mReader.init();
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);

            mypDialog.cancel();

            if (!result) {
                Toast.makeText(GgjsyztActivity.this, "init fail",
                        Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();

            mypDialog = new android.app.ProgressDialog(GgjsyztActivity.this);
            mypDialog.setProgressStyle(android.app.ProgressDialog.STYLE_SPINNER);
            mypDialog.setMessage("init...");
            mypDialog.setCanceledOnTouchOutside(false);
            mypDialog.show();
        }
    }

    public boolean vailHexInput(String str) {

        if (str == null || str.length() == 0) {
            return false;
        }

        // ���ȱ�����ż��
        if (str.length() % 2 == 0) {
            return StringUtility.isHexNumberRex(str);
        }

        return false;
    }

    HashMap<Integer, Integer> soundMap = new HashMap<Integer, Integer>();
    private SoundPool soundPool;
    private float volumnRatio;
    private AudioManager am;
    private void initSound(){
        soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 5);
        soundMap.put(1, soundPool.load(this, R.raw.barcodebeep, 1));
        soundMap.put(2, soundPool.load(this, R.raw.serror, 1));
        am = (AudioManager) this.getSystemService(AUDIO_SERVICE);// 实例化AudioManager对象
    }
    /**
     * 播放提示音
     *
     * @param id 成功1，失败2
     */
    public void playSound(int id) {

        float audioMaxVolumn = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC); // 返回当前AudioManager对象的最大音量值
        float audioCurrentVolumn = am.getStreamVolume(AudioManager.STREAM_MUSIC);// 返回当前AudioManager对象的音量值
        volumnRatio = audioCurrentVolumn / audioMaxVolumn;
        try {
            soundPool.play(soundMap.get(id), volumnRatio, // 左声道音量
                    volumnRatio, // 右声道音量
                    1, // 优先级，0为最低
                    0, // 循环次数，0无不循环，-1无永远循环
                    1 // 回放速度 ，该值在0.5-2.0之间，1为正常速度
            );
        } catch (Exception e) {
            e.printStackTrace();

        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == 293) {
            if (event.getRepeatCount() == 0) {
                read();
            }
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

    @Bind(R.id.scan)
    Button scan;
    private void read(){

        if(isLoop==true){
            isLoop = false;
            scan.setText("扫描");
        }else {
            scan.setText("停止");
            isLoop = true;
            new TagThread().start();
        }
    }
    private boolean isLoop= false;
    class TagThread extends Thread {
        public void run() {
            while (isLoop) {
                read1();
            }
        }
    }


    private void read1() {
        String ptrStr = "0";


        String cntStr = "4";

        String pwdStr = "00000000";

        boolean result=false;
        String Bank="RESERVED";
        boolean cbfitter = false;
        boolean QT = false;
        if (cbfitter)//  过滤
        {



            int filterPtr=32;
            String filterData="";
            int filterCnt=0;
            String filterBank="UII";

            String data="";
            if(QT) {
                data =mReader.readDataWithQT(pwdStr,
                        RFIDWithUHF.BankEnum.valueOf(filterBank),
                        filterPtr,
                        filterCnt,
                        filterData,
                        RFIDWithUHF.BankEnum.valueOf(Bank),
                        Integer.parseInt(ptrStr),
                        Integer.parseInt(cntStr)
                );
            }else{
                data =mReader.readData(pwdStr,
                        RFIDWithUHF.BankEnum.valueOf(filterBank),
                        filterPtr,
                        filterCnt,
                        filterData,
                        RFIDWithUHF.BankEnum.valueOf(Bank),
                        Integer.parseInt(ptrStr),
                        Integer.parseInt(cntStr)
                );
            }
            if(data!=null && data.length()>0){
                result=true;
            }else {
                result=false;
            }

            final String finalData = data;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    select(finalData);
                }
            });

            //data
            //EtData_Read.setText("data：" +data);
        } else {
            SimpleRFIDEntity entity;
            if(QT){
                entity= mReader.readDataWithQT(pwdStr,
                        RFIDWithUHF.BankEnum.valueOf(Bank),
                        Integer.parseInt(ptrStr),
                        Integer.parseInt(cntStr));
            }else {
                entity = mReader.readData(pwdStr,
                        RFIDWithUHF.BankEnum.valueOf(Bank),
                        Integer.parseInt(ptrStr),
                        Integer.parseInt(cntStr));
            }
            if (entity != null) {
                result = true;
                final String finalData = entity.getData();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        select(finalData);
                    }
                });
                //select(entity.getData());
                //shortToast("读取成功:"+entity.getData());
                //EtData_Read.setText("data：" + entity.getData());
            } else {
                result = false;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        shortToast("读取失败");
                    }
                });

                //UIHelper.ToastMessage(mContext, R.string.uhf_msg_read_data_fail);
                //EtData_Read.setText("");
            }
        }
        if(!result){
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    playSound(2);
                }
            });

        }else{
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    playSound(1);
                }
            });

        }
    }
    @OnClick(R.id.clear)
    public void clear(){
        adapter.clearSelect();
    }

    @OnClick(R.id.ruku)
    public void rukuClick(){
        startActivity(RukuActivity.class);
    }
}